import jsonp from "jsonp";

const jsonpInstance = (url: string) => {
  // 请求 JSONP 数据
  return new Promise((resolve, reject) => {
    jsonp(url, { name: "jsonpCallback" }, (err, d) => {
      if (err) {
        console.error("JSONP 请求失败：", err);
        reject(err);
      } else {
        console.log("JSONP 数据解析成功：", d);
        resolve(d);
      }
    });
  });
};

const getCarModelCompatibleYear = async () => {
  const url = "https://www.carqueryapi.com/api/0.3/?cmd=getYears"; // 确保 URL 是正确的
  // 请求 JSONP 数据
  return jsonpInstance(url);
};

const getCarModelCompatibleMaker = (year: string) => {
  const url = `https://www.carqueryapi.com/api/0.3/?cmd=getMakes&year=${year}&sold_in_us=1`;
  // 请求 JSONP 数据
  return jsonpInstance(url);
};

const getCarModelCompatibleModel = (year: string, make: string) => {
  const url = `https://www.carqueryapi.com/api/0.3/?cmd=getModels&make=${make}&year=${year}&sold_in_us=1`;
  // 请求 JSONP 数据
  return jsonpInstance(url);
};

const getCarModelCompatibleTrim = (
  year: string,
  make: string,
  model: string
) => {
  const url = `https://www.carqueryapi.com/api/0.3/?cmd=getTrims&make=${make}&model=${model}&year=${year}&sold_in_us=1`;
  // 请求 JSONP 数据
  return jsonpInstance(url);
};

export {
  getCarModelCompatibleYear,
  getCarModelCompatibleTrim,
  getCarModelCompatibleMaker,
  getCarModelCompatibleModel,
};
